﻿using FastData.Caching;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System;
using System.Data.Common;
using System.Linq.Expressions;

namespace FastData
{
    public class DeleteQuery<T> : QueryBase<T> where T : new()
    {
        internal DeleteQuery(DataAccess data, T entity)
            : base(data)
        {
            if (entity != null)
            {
                var properties = typeof(T).GetDataProperties().Where(prop => prop.IsKey());

                foreach (PropertyInfo prop in properties)
                {
                    SetWhere(prop.Name, prop.GetValue(entity));
                }
            }
        }

        internal override string GetCommandText(ExecuteType type)
        {
            return Data.Provider.CreateDeleteText(this, type);
        }

        public DeleteQuery<T> Where(Expression<Func<T, bool>> expression)
        {
            SetWhere(expression);
            return this;
        }

        public void ExecuteLazy()
        {
            Data.ExecuteLazy(this);
        }

        public int Execute()
        {
            return Data.ExecuteNonQuery(this);
        }

        internal override void ExecuteCompleted()
        {
            CacheProvider.Remove(new TableDependency(TableName));
        }
    }

}
